package com.example.customizedgroupmessage;

import java.util.ArrayList;

import com.example.customizedgroupmessage.SMSMemberListView.getContactThread;

import android.app.*;
import android.content.*;
import android.database.*;
import android.net.Uri;
import android.os.*;
import android.provider.*;
import android.view.View;
import android.widget.*;
import android.util.Log;

public class MailGroupListView extends Activity {
	// 요청 코드
	public static final int REQUEST_CODE_MAILMEMBERLISTVIEW=2002;
	// Log TAG
	//private static final String TAG1 = "Group TAG";
	// 그룹 저장할 배열
	ArrayList<Group> arrlistGroup;
	ArrayList<String> arrGroup;
	ArrayAdapter<String> Adapter;
	getAllCountThread mThread;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sms_group_listview);

		arrlistGroup = new ArrayList<Group>();
		arrlistGroup.clear();
		Group temp1 = new Group("-1", "전체 목록", 0/*getAllCount()*/);
		arrlistGroup.add(temp1);
		mThread = new getAllCountThread();
		mThread.setDaemon(true);
		mThread.start();
		
		Uri uri = ContactsContract.Groups.CONTENT_URI;

		String[] projection = new String[] {
		    ContactsContract.Groups._ID,
		    ContactsContract.Groups.TITLE,
		    ContactsContract.Groups.ACCOUNT_NAME,
		    ContactsContract.Groups.ACCOUNT_TYPE,
		    ContactsContract.Groups.DELETED,
		    ContactsContract.Groups.GROUP_VISIBLE
		};
		
		//String selection = ContactsContract.Groups.DELETED + "=0" + " AND " + 
		//						ContactsContract.Groups.GROUP_VISIBLE + "=1";
		String selection = null;
		String sortOrder = null;
		
		Cursor cursor = getContentResolver().query(uri, projection, selection, null, sortOrder);
		String groupId = null;
		String groupType = null;
		String groupTitle = null;
		String accountName = null;
		int groupCount = 0;

		while (cursor.moveToNext()) {
			/*
			Log.d(TAG1, "Id ===> " + cursor.getString(0));
			Log.d(TAG1, "Title ===> " + cursor.getString(1));
			Log.d(TAG1, "Account Name ===> " + cursor.getString(2));
			Log.d(TAG1, "Account Type ===> " + cursor.getString(3));
			Log.d(TAG1, "Deleted ===> " + cursor.getString(4));
			Log.d(TAG1, "Visible ===> " + cursor.getString(5));
			*/
			   
			groupId = cursor.getString(0);
			groupTitle = cursor.getString(1);
			groupType = cursor.getString(3);
			groupCount = getGroupSummaryCount(cursor.getString(0));
			
			Group temp = new Group(groupId, groupTitle, groupCount);
			arrlistGroup.add(temp);
		}
		cursor.close();
		
		arrGroup = new ArrayList<String>();
		for(int i=0; i<arrlistGroup.size(); i++){
			if(i==0){
				arrGroup.add(arrlistGroup.get(i).getGroupTitle());
			}
			else{
				arrGroup.add(arrlistGroup.get(i).getGroupTitle() + " (" + arrlistGroup.get(i).getGroupCount() + ")");
			}
			//arrGroup.add(arrlistGroup.get(i).getGroupTitle());
		}
		
		// 어댑터 준비
		Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrGroup);

		// 리스트뷰에 어탭터 연결
		ListView list = (ListView)findViewById(R.id.sms_group_list);
		list.setAdapter(Adapter);
		// 이벤트 핸들러 연결
		list.setOnItemClickListener(mItemClickListener);
	}
	
	// OnClick 이벤트 핸들러
	AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			Intent intent = new Intent(MailGroupListView.this, MailMemberListView.class);
			intent.putExtra("SelectedGroup", arrlistGroup.get(position).getGroupTitle());
			intent.putExtra("SelectedGroupId", arrlistGroup.get(position).getGroupId());
			startActivityForResult(intent, REQUEST_CODE_MAILMEMBERLISTVIEW);
		}
	};
	
	
	// 그룹 멤버 수 카운트하기
	private int getGroupSummaryCount(String groupId) {

/*		Uri uri = ContactsContract.Data.CONTENT_URI;
		String[] projection = new String[] {ContactsContract.CommonDataKinds.GroupMembership.RAW_CONTACT_ID};
		String selection = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + " = " + groupId + " AND " 
				+ ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + " = '" 
				+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'";*/
		Uri uri = ContactsContract.Data.CONTENT_URI;
		String[] projection = new String[] {ContactsContract.CommonDataKinds.GroupMembership.RAW_CONTACT_ID};
		String selection = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + " = " + groupId;
		
		Cursor cursor = getContentResolver().query(uri, projection, selection, null, null);
		
		int count = 0;
		String mail = null;
		String id = null;
		
		while (cursor.moveToNext()) {
			id = cursor.getString(0);
			
			// 메일 주소 서브 쿼리
			Cursor mailCursor = getContentResolver().query(ContactsContract.CommonDataKinds.
					Email.CONTENT_URI, null, 
					ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
					new String[]{id}, null);

			int mtypeidx = mailCursor.getColumnIndex(
					ContactsContract.CommonDataKinds.Email.TYPE);
			int mailidx = mailCursor.getColumnIndex(
					ContactsContract.CommonDataKinds.Email.ADDRESS);

			// 메일 타입에 따라 여러 개가 존재한다.
			while (mailCursor.moveToNext()) {
				String addr = mailCursor.getString(mailidx);
				if(mailCursor.getInt(mtypeidx)>0){
					mail = addr;
				}
				else {
					mail = mailCursor.getString(
							mailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
				}
			}
			mailCursor.close();
			
			if(mail != null){
				count++;
			}
			mail = null;
		}
		cursor.close();
		return count;
	}
	
	Handler mHandler = new Handler() {
		@SuppressWarnings("deprecation")
		public void handleMessage(Message msg) {
			arrGroup.set(0, "전체 목록 ("+msg.what+")");
			Adapter.notifyDataSetChanged();
		}
	};
	
	// 전체 멤버 수 카운트하기
	class getAllCountThread extends Thread {
		public void run() {
			Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
			int count = 0;
			int ididx = cursor.getColumnIndex(ContactsContract.Contacts._ID);
			String mail = null;
			String id = null;
			
			while (cursor.moveToNext()) {
				id = cursor.getString(ididx);
				
				// 메일 주소 서브 쿼리
				Cursor mailCursor = getContentResolver().query(ContactsContract.CommonDataKinds.
						Email.CONTENT_URI, null, 
						ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
						new String[]{id}, null);

				int mtypeidx = mailCursor.getColumnIndex(
						ContactsContract.CommonDataKinds.Email.TYPE);
				int mailidx = mailCursor.getColumnIndex(
						ContactsContract.CommonDataKinds.Email.ADDRESS);

				// 메일 타입에 따라 여러 개가 존재한다.
				while (mailCursor.moveToNext()) {
					String addr = mailCursor.getString(mailidx);
					if(mailCursor.getInt(mtypeidx)>0){
						mail = addr;
					}
					else {
						mail = mailCursor.getString(
								mailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
					}
				}
				mailCursor.close();
				
				if(mail != null){
					count++;
				}
				mail = null;
			}
			cursor.close();
			
			//Message msg = mHandler.obtainMessage();
			//msg.what = 0;
			//msg.arg1 = count;
			//mHandler.sendMessage(msg);
			mHandler.sendEmptyMessage(count);
		}
	}
	
	
	// 전체 멤버 수 카운트하기
	private int getAllCount() {

		Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
		int count = 0;
		int ididx = cursor.getColumnIndex(ContactsContract.Contacts._ID);
		String mail = null;
		String id = null;
		
		while (cursor.moveToNext()) {
			id = cursor.getString(ididx);
			
			// 메일 주소 서브 쿼리
			Cursor mailCursor = getContentResolver().query(ContactsContract.CommonDataKinds.
					Email.CONTENT_URI, null, 
					ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
					new String[]{id}, null);

			int mtypeidx = mailCursor.getColumnIndex(
					ContactsContract.CommonDataKinds.Email.TYPE);
			int mailidx = mailCursor.getColumnIndex(
					ContactsContract.CommonDataKinds.Email.ADDRESS);

			// 메일 타입에 따라 여러 개가 존재한다.
			while (mailCursor.moveToNext()) {
				String addr = mailCursor.getString(mailidx);
				if(mailCursor.getInt(mtypeidx)>0){
					mail = addr;
				}
				else {
					mail = mailCursor.getString(
							mailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
				}
			}
			mailCursor.close();
			
			if(mail != null){
				count++;
			}
			mail = null;
		}
		cursor.close();
		return count;
	}
}